import base64
import uuid

from fastapi import FastAPI, Request, Form, HTTPException, status, Depends
from fastapi.responses import HTMLResponse, RedirectResponse
from fastapi.staticfiles import StaticFiles
from fastapi.templating import Jinja2Templates
from fastapi.security import HTTPBearer, HTTPAuthorizationCredentials
from typing import List
from datetime import timedelta
import uvicorn

# 导入自定义模块
from models import (
    init_database, get_user_functions, get_user_car_models
)
from auth import create_access_token, verify_token, get_current_user, authenticate_user
from services import generate_qr_code, del_old_pic

app = FastAPI(title="QR Generator API", version="1.0.0")

# 挂载静态文件
app.mount("/static", StaticFiles(directory="static"), name="static")

# 模板配置
templates = Jinja2Templates(directory="templates")

# # 车型列表
# CAR_MODELS = ["摇光", "瑞虎9", "虎8L", "艾瑞泽8"]


# # 功能列表（模拟从数据库获取）
# FUNCTION_LIST = [
#     "小鹿灯", "功放", "记录仪", "盲区检测", "倒车侧向制动",
#     "紧急车道保持", "索尼音效", "微波雷达", "抬头显示", 
#     "香氛系统", "方向盘加热  座椅通风", "前雷达开关", 
#     "座椅开关", "北斗 hicar", "逸8155","尚360"
# ]

# 初始化数据库
init_database()


@app.get("/", response_class=HTMLResponse)
async def read_root(request: Request):
    """根路由 - 重定向到登录页"""
    return RedirectResponse(url="/login")


@app.get("/login", response_class=HTMLResponse)
async def login_page(request: Request):
    """登录页面"""
    return templates.TemplateResponse("login.html", {"request": request})


@app.get("/dashboard", response_class=HTMLResponse)
async def dashboard(request: Request):
    """主页面（需要认证）"""
    return templates.TemplateResponse("index.html", {"request": request})


@app.get("/admin", response_class=HTMLResponse)
async def admin_page(request: Request):
    """管理员页面（需要管理员权限）"""
    return templates.TemplateResponse("admin.html", {"request": request})


@app.post("/api/login")
async def login(
    username: str = Form(...),
    password: str = Form(...),
    remember_me: bool = Form(False)
):
    """用户登录接口"""
    user = authenticate_user(username, password)
    if not user:
        raise HTTPException(
            status_code=status.HTTP_401_UNAUTHORIZED,
            detail="用户名或密码错误"
        )
    
    # 创建访问令牌
    access_token_expires = timedelta(minutes=30 if not remember_me else 60*24*7)  # 7天
    access_token = create_access_token(
        data={"sub": user.username}, expires_delta=access_token_expires
    )
    
    return {
        "success": True,
        "access_token": access_token,
        "token_type": "bearer",
        "username": user.username,
        "is_admin": user.is_admin
    }


@app.post("/api/verify-token")
async def verify_token_endpoint(credentials: HTTPAuthorizationCredentials = Depends(HTTPBearer())):
    """验证令牌接口"""
    token = credentials.credentials
    username = verify_token(token)
    return {"valid": username is not None, "username": username}


@app.post("/api/create-user")
async def create_user(
    username: str = Form(...),
    email: str = Form(...),
    password: str = Form(...),
    functions: List[str] = Form([]),
    car_models: List[str] = Form([]),
    generate_limit: int = Form(100),
    current_user = Depends(get_current_user)
):
    from models import User, Function, UserFunction, CarModel, UserCarModel, get_password_hash
    if not current_user.is_admin:
        raise HTTPException(status_code=403, detail="只有管理员可以创建用户")
    try:
        if User.select().where(User.username == username).exists():
            raise HTTPException(status_code=400, detail="用户名已存在")
        if User.select().where(User.email == email).exists():
            raise HTTPException(status_code=400, detail="邮箱已存在")
        hashed_password = get_password_hash(password)
        new_user = User.create(
            username=username,
            email=email,
            hashed_password=hashed_password,
            is_active=True,
            is_admin=False,
            generate_limit=generate_limit
        )
        for function_name in functions:
            try:
                function = Function.get(Function.name == function_name)
                UserFunction.create(user=new_user, function=function)
            except Function.DoesNotExist:
                continue
        for car_name in car_models:
            try:
                car = CarModel.get(CarModel.name == car_name)
                UserCarModel.create(user=new_user, car_model=car)
            except CarModel.DoesNotExist:
                continue
        return {"success": True, "message": "用户创建成功", "user_id": new_user.id, "username": new_user.username}
    except Exception as e:
        raise HTTPException(status_code=500, detail=f"创建用户失败: {str(e)}")


@app.get("/api/functions")
async def get_functions(current_user = Depends(get_current_user)):
    """获取功能列表接口（根据用户权限返回）"""
    user_functions = get_user_functions(current_user)
    function_names = [func.name for func in user_functions]
    return {"functions": function_names}


@app.get("/api/all-functions")
async def get_all_functions(current_user = Depends(get_current_user)):
    """获取所有功能列表接口（仅管理员可用）"""
    from models import Function
    
    # 检查是否为管理员
    if not current_user.is_admin:
        raise HTTPException(
            status_code=status.HTTP_403_FORBIDDEN,
            detail="只有管理员可以访问所有功能列表"
        )
    
    all_functions = list(Function.select().where(Function.is_active == True))
    function_names = [func.name for func in all_functions]
    return {"functions": function_names}


@app.get("/api/users")
async def get_users(current_user = Depends(get_current_user)):
    from models import User, UserFunction, Function, UserCarModel, CarModel
    if not current_user.is_admin:
        raise HTTPException(status_code=403, detail="只有管理员可以访问用户列表")
    users = []
    for user in User.select():
        if user.is_admin:
            user_functions = list(Function.select().where(Function.is_active == True))
            user_car_models = list(CarModel.select().where(CarModel.is_active == True))
        else:
            user_functions = list(Function.select().join(UserFunction).where(
                UserFunction.user == user,
                Function.is_active == True
            ))
            user_car_models = list(CarModel.select().join(UserCarModel).where(
                UserCarModel.user == user,
                CarModel.is_active == True
            ))
        users.append({
            "id": user.id,
            "username": user.username,
            "email": user.email,
            "is_admin": user.is_admin,
            "is_active": user.is_active,
            "created_at": user.created_at.isoformat(),
            "functions": [func.name for func in user_functions],
            "car_models": [cm.name for cm in user_car_models],
            "generate_limit": user.generate_limit
        })
    return {"users": users}


@app.post("/api/generate")
async def generate_qr(
    input_text: str = Form(...),
    car_model: str = Form(...),
    functions: List[str] = Form(...),
    current_user=Depends(get_current_user)
):
    print(f"car_model: {car_model}, functions: {functions}")
    from models import User, GenerateHistory
    if not current_user.is_admin:
        if current_user.generate_limit <= 0:
            current_user.is_active = False
            current_user.save()
            raise HTTPException(status_code=403, detail="调用次数已用完，账号已被禁用，请联系管理员")
        current_user.generate_limit -= 1
        current_user.save()
        if current_user.generate_limit == 0:
            current_user.is_active = False
            current_user.save()
    pic_file_path = f"tmp_pic/{current_user.username}-{uuid.uuid4().hex}.png"
    qr_code_str = generate_qr_code(input_text, car_model, functions, pic_file_path)
    with open(pic_file_path, "rb") as f:
        pic = f.read()
        pic_base64 = base64.b64encode(pic).decode()
    del_old_pic()
    # 写入历史
    GenerateHistory.create(
        user=current_user,
        car_model=car_model,
        functions=','.join(functions),
        input_text=input_text,
        output_number=qr_code_str
    )
    return {
        "success": True,
        "message": "二维码生成成功",
        "data": {
            "input_text": input_text,
            "car_model": car_model,
            "functions": functions,
            # "qr_code": "base64_encoded_image_placeholder",
            "qr_code": pic_base64,
            "output_number": qr_code_str
        }
    }


@app.get("/api/history")
async def get_history(current_user=Depends(get_current_user)):
    from models import GenerateHistory
    records = (GenerateHistory
        .select()
        .where(GenerateHistory.user == current_user)
        .order_by(GenerateHistory.created_at.desc()))
        # .limit(30))
    result = [
        {
            "created_at": r.created_at.strftime('%Y-%m-%d %H:%M:%S'),
            "car_model": r.car_model,
            "functions": r.functions.split(',') if r.functions else [],
            "input_text": r.input_text,
            "output_number": r.output_number
        }
        for r in records
    ]
    return {"history": result}


@app.post("/api/clear")
async def clear_data(current_user=Depends(get_current_user)):
    """清除数据接口（需要认证）"""
    # TODO: 实现清除逻辑
    return {"success": True, "message": "数据清除成功"}


@app.get("/api/car-models")
async def get_car_models(current_user = Depends(get_current_user)):
    """获取用户可用车型列表（带权限）"""
    user_car_models = get_user_car_models(current_user)
    car_model_names = [cm.name for cm in user_car_models]
    return {"car_models": car_model_names}


@app.get("/api/all-car-models")
async def get_all_car_models(current_user = Depends(get_current_user)):
    """获取所有车型列表（仅管理员）"""
    from models import CarModel
    if not current_user.is_admin:
        raise HTTPException(
            status_code=status.HTTP_403_FORBIDDEN,
            detail="只有管理员可以访问所有车型列表"
        )
    all_car_models = list(CarModel.select().where(CarModel.is_active == True))
    car_model_names = [cm.name for cm in all_car_models]
    return {"car_models": car_model_names}


@app.post("/api/toggle-user-status")
async def toggle_user_status(
    user_id: int = Form(...),
    current_user = Depends(get_current_user)
):
    from models import User
    if not current_user.is_admin:
        raise HTTPException(status_code=403, detail="只有管理员可以操作")
    try:
        user = User.get_by_id(user_id)
        if user.username == 'admin':
            raise HTTPException(status_code=400, detail="不能禁用管理员账号")
        user.is_active = not user.is_active
        user.save()
        return {"success": True, "is_active": user.is_active}
    except User.DoesNotExist:
        raise HTTPException(status_code=404, detail="用户不存在")


@app.post("/api/update-user")
async def update_user(
    user_id: int = Form(...),
    functions: List[str] = Form([]),
    car_models: List[str] = Form([]),
    generate_limit: int = Form(None),
    current_user = Depends(get_current_user)
):
    from models import User, Function, UserFunction, CarModel, UserCarModel
    if not current_user.is_admin:
        raise HTTPException(status_code=403, detail="只有管理员可以操作")
    try:
        user = User.get_by_id(user_id)
        if user.username == 'admin':
            raise HTTPException(status_code=400, detail="不能修改管理员账号")
        UserFunction.delete().where(UserFunction.user == user).execute()
        for fname in functions:
            try:
                func = Function.get(Function.name == fname)
                UserFunction.create(user=user, function=func)
            except Function.DoesNotExist:
                continue
        UserCarModel.delete().where(UserCarModel.user == user).execute()
        for cname in car_models:
            try:
                car = CarModel.get(CarModel.name == cname)
                UserCarModel.create(user=user, car_model=car)
            except CarModel.DoesNotExist:
                continue
        if generate_limit is not None:
            user.generate_limit = generate_limit
            user.save()
        return {"success": True}
    except User.DoesNotExist:
        raise HTTPException(status_code=404, detail="用户不存在")


if __name__ == "__main__":
    uvicorn.run(app, host="0.0.0.0", port=8000)
